package com.nyc.boot;

import com.nyc.anno.WebServer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;

/**
 * @author 26917
 */
public class SpringApplication {

    public static ConfigurableApplicationContext run(Class clazz) {
        //创建Spring容器 扫描业务bean
        AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
        applicationContext.register(clazz);
        applicationContext.refresh();
        //启动tomcat/jetty
        WebServer webServer = getWebServer(applicationContext);
        webServer.start();
        return applicationContext;
    }

    private static WebServer getWebServer(ApplicationContext applicationContext) {
        // key为beanName, value为Bean对象
        Map<String, WebServer> webServers = applicationContext.getBeansOfType(WebServer.class);

        if (webServers.isEmpty()) {
            throw new NullPointerException();
        }
        if (webServers.size() > 1) {
            throw new IllegalStateException();
        }

        // 返回唯一的一个
        return webServers.values().stream().findFirst().get();
    }
}
